﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using IHISCETeim.Library;
using Newtonsoft.Json;
using IHISCETeim.BLL;
using IHISCETeim.Model;
namespace IHISCETeim.Web.MachineSys.uploadify
{
    public partial class upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SLogInfo log=new SLogInfo();
            log.LogType="文件上传";
            log.OpDate=DateTime.Now;
            log.OpType="开始上传";
            log.RealName=OUserController.CurrentUser.RealName;
            log.DWZRef="IHISCETeim.Web.MachineSys.uploadify.upload";

            SLogController.Add(log);
            //if (string.IsNullOrEmpty(Request["infoid"].ToString()))
            //{
            //    Response.Write("{'err':'" + jsonString("非法上传") + "','msg':''}");
            //    return;
            //}
            Response.Charset = "UTF-8";

            // 初始化一大堆变量
            string inputname = "filedata";//表单文件域name
            string attachdir = "/upload";     // 上传文件保存路径，结尾不要带/
            int dirtype = 0;                 // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存

            try
            {
                dirtype = Convert.ToInt32(Request["dirtype"].ToString());
            }
            catch
            {
                dirtype = 2;
            }
            //获取客户端 控件ID
            string clientId = "";
            try
            {
                clientId = Request["clientId"].ToString();
            }
            catch
            {
                clientId = "";
            }
            //获取存储子文件夹名称
            string foldername = Request.GetRequestValue<string>("foldername", true, "其它");

            int maxattachsize = 10485760;     // 最大上传大小，默认是4M
            string upext = "zip,rar,txt,xls,doc,xlsx,docx,jpg,jpeg,gif,png,bmp,swf,avi,mp3,wma,mid,wma,pdf";    // 上传扩展名
            switch (dirtype)
            {
                case 4://来自经销商平台
                    maxattachsize = 10485760;//最大10M
                    upext = "zip,rar,jpg,jpeg,gif,png,bmp,swf,avi,tif";
                    break;
                default:
                    break;
            }
            byte[] file;                     // 统一转换为byte数组处理
            string localname = "";           

            string err = "";
            string msg = "''";
            string target = "";
            
            HttpFileCollection filecollection = Request.Files;
            HttpPostedFile postedfile = filecollection.Get(inputname);

            // 读取原始文件名
            localname = postedfile.FileName;
            // 初始化byte长度.
            file = new Byte[postedfile.ContentLength];

            // 转换为byte类型
            System.IO.Stream stream = postedfile.InputStream;
            stream.Read(file, 0, postedfile.ContentLength);
            stream.Close();

            filecollection = null;
           

            if (file.Length == 0) err = "上传失败:无数据提交";
            else
            {
                if (file.Length > maxattachsize) err = "上传失败:文件大小超过" + ((maxattachsize / 1024) / 1024).ToString() + "M";
                else
                {
                    string attach_dir, attach_subdir, filename, extension;

                    // 取上载文件后缀名
                    extension = GetFileExt(localname);

                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上传失败:上传文件扩展名必需为：" + upext;
                    else
                    {
                        switch (dirtype)
                        {
                            case 0:
                                attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                                break;
                            case 2:
                                attach_subdir = "month_" + DateTime.Now.ToString("yyyyMM");
                                break;
                            case 3://不适合品处理票上传供应商回复
                                attach_subdir = "OUnsuitableProd" ;
                                break;
                            case 4://经销商平台 上传品情图片                               
                                attach_subdir = "AgnetSys/" + foldername + "/" + DateTime.Now.ToString("yyyyMM");
                                break;
                            case 5://经销商平台 上传保修卡扫描件                               
                                attach_subdir = "AgnetSys/" + foldername + "/UWarrantyCard";
                                break;
                            case 6://经销商平台 上传新机入库检查NG项图片                              
                                attach_subdir = "AgnetSys/" + foldername + "/UAgentMacList";
                                break;
                            case 20://重点品资对策上传目录
                                attach_subdir = "OQualityStrategy/" + DateTime.Now.ToString("yyyyMM");
                                break;
                            default:
                                attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                                break;
                        }
                        attach_dir = attachdir + "/" + attach_subdir + "/";

                        // 生成随机文件名
                        Random random = new Random(DateTime.Now.Millisecond);
                        filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;

                        target = attach_dir + filename;
                        try
                        {
                            CreateFolder(Server.MapPath(attach_dir));

                            System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            fs.Write(file, 0, file.Length);
                            fs.Flush();
                            fs.Close();
                            err = "";
                            //
                            if (dirtype == 4)//创建小图
                                AgentPageBase.CreateSmallPic(Server.MapPath(target));
                        }
                        catch (Exception ex)
                        {
                            err = "上传失败:"+ex.Message.ToString();
                            target = "";
                        }                       
                    }
                }
            }
            if (dirtype == 0)
            {
                json tem = new json() { err = "", msg = target };
                Response.Write(JsonConvert.SerializeObject(tem));
                return;
            }
         


            file = null;
            uploadResultInfo resultInfo = new uploadResultInfo();
            resultInfo.uploadResult = err.IsEmptyOrNull();
            resultInfo.errMsg = err;
            resultInfo.filePath = target;
            resultInfo.customerInfo = clientId;
            resultInfo.soureFileName = localname;

            /**/

            log = new SLogInfo();
            log.LogType = "文件上传";
            log.OpDate = DateTime.Now;
            log.OpType = "完成上传";
            log.RealName = OUserController.CurrentUser.RealName;
            log.DWZRef = "IHISCETeim.Web.MachineSys.uploadify.upload";
            log.OpNewObj = resultInfo.SerializableToXml();
            SLogController.Add(log);


            Response.Clear();
            Response.ContentType = "application/json";                       
            Response.Write(JsonConvert.SerializeObject(resultInfo));
        }

        public class json { public string err { get; set; } public string msg { get; set; } }

        [Serializable]
        public class uploadResultInfo
        {
            /// <summary>
            /// 上传结果,TRUE成功
            /// </summary>
            public bool uploadResult { get; set; }
            /// <summary>
            /// 上传失败消息
            /// </summary>
            public string errMsg { get; set; }
            /// <summary>
            /// 成功上传后文件路径
            /// </summary>
            public string filePath { get; set; }
            /// <summary>
            /// 回传的用户信 息
            /// </summary>
            public string customerInfo { get; set; }
            /// <summary>
            /// 原文件名称
            /// </summary>
            public string soureFileName { get; set; }
        }

        string jsonString(string str)
        {
            str = str.Replace("\\", "\\\\");
            str = str.Replace("/", "\\/");
            str = str.Replace("'", "\\'");
            return str;
        }


        string GetFileExt(string FullPath)
        {
            if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
            else return "";
        }

        void CreateFolder(string FolderPath)
        {
            if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
        }
    }
}